﻿using Aliyun.TableStore;
using Aliyun.TableStore.DataModel;
using Aliyun.TableStore.Request;
using Aliyun.TableStore.Response;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using Wicture.DbRESTFul;
using Wicture.QPZS.EPC.Models;

namespace Wicture.QPZS.EPC
{
    /// <summary>
    /// 从阿里去OTS服务查询VIN信息
    /// </summary>
    public static class OTSVinService
    {
        private static Lazy<OTSClient> client = new Lazy<OTSClient>(InitOTSClient);
        private static string ImageCDNUrl;
        private readonly static string _tableName = "vin";

        public static string QueryBrandCode(string vin)
        {
            return Query(vin)?.brandCode;
        }

        public static Vin QueryModelInfo(string vin)
        {
            return Query(vin);
        }


        private static Vin Query(string key)
        {
            PrimaryKey primaryKey = new PrimaryKey();
            primaryKey.Add("vin", new ColumnValue(key));

            var sw = LoggerManager.StartWatch();
            GetRowRequest request = new GetRowRequest("vin", primaryKey);
            GetRowResponse response = client.Value.GetRow(request);
            if (response.Attribute.Count == 0)
            {
                return null;
            }
            var body = response.Attribute["body"].BinaryValue;
            var text = Compression.UnprotectAndUnzip(body);
            var result = JsonConvert.DeserializeObject<Vin>(text);
            if (!string.IsNullOrEmpty(result.imageUrl) && !result.imageUrl.StartsWith("http"))
            {
                result.imageUrl = $"{ImageCDNUrl}{result.imageUrl}";
            }
            LoggerManager.EndWatch(sw);
            return result;
        }

        private static OTSClient InitOTSClient()
        {
            ImageCDNUrl = ConfigurationManager.Settings.Variables["Qiniu.ImageDomain"];

            var tsConfig = new TableStoreConfig();
            OTSClientConfig config = new OTSClientConfig(tsConfig.Endpoint, tsConfig.AccessKeyId, tsConfig.AccessKeySecret, tsConfig.InstanceName);
            config.OTSDebugLogHandler = null;
            config.OTSErrorLogHandler = new OTSClientConfig.OTSLogHandler(msg => LoggerManager.Logger.LogError(msg));
            return new OTSClient(config);
        }

        public static void SaveOTS(string key, Vin vinModel)
        {
            PrimaryKey primaryKey = new PrimaryKey();
            primaryKey.Add("vin", new ColumnValue(key));

            // 定义要写入改行的属性列
            AttributeColumns attribute = new AttributeColumns();
            var body = Compression.ZipAndProtect(vinModel);
            attribute.Add("body", new ColumnValue(body));

            var request = new PutRowRequest(_tableName, new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);
            var response = client.Value.PutRow(request);
        }

        public static object ClearVin(string vinCode)
        {
            PrimaryKey primaryKey = new PrimaryKey();
            primaryKey.Add("vin", new ColumnValue(vinCode));

            var request = new DeleteRowRequest(_tableName, new Condition(RowExistenceExpectation.IGNORE), primaryKey);
            return client.Value.DeleteRow(request);
        }
    }
}
